<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <i class="fa fa-angle-left" @click="goBack"></i>
      <p>我的钱包</p>
      <i class="fa fa-list" @click="goToTransactions"></i>
    </header>

    <!-- 余额展示部分 -->
    <div class="balance-section">
      <div class="balance-card">
        <div class="balance-title">钱包余额（元）</div>
        <div class="balance-amount">{{ formatPrice(walletBalance.availableBalance) }}</div>
        <div class="balance-detail">
          <div class="detail-item">
            <span>可用余额</span>
            <span>&#165;{{ formatPrice(walletBalance.availableBalance) }}</span>
          </div>
          <div class="detail-item">
            <span>冻结金额</span>
            <span>&#165;{{ formatPrice(walletBalance.frozenBalance) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作按钮部分 -->
    <div class="action-section">
      <div class="action-buttons">
        <button class="recharge-btn" @click="showRechargeDialog">
          <i class="fa fa-plus-circle"></i>
          <span>充值</span>
        </button>
        <button class="withdraw-btn" @click="showWithdrawDialog">
          <i class="fa fa-money"></i>
          <span>提现</span>
        </button>
      </div>

      <!-- 冻结资金提示 -->
      <div v-if="walletBalance.frozenBalance > 0" class="frozen-notice">
        <i class="fa fa-info-circle"></i>
        <div class="frozen-info">
          <p class="frozen-title">资金冻结中</p>
          <p class="frozen-desc">冻结金额：¥{{ formatPrice(walletBalance.frozenBalance) }}</p>
          <p class="frozen-desc">等待买家确认收货后自动解冻</p>
        </div>
      </div>
    </div>

    <!-- 快捷入口与功能说明 -->
    <div class="info-cards">
      <div class="info-card" @click="goToTransactions">
        <div class="info-icon">
          <i class="fa fa-list-alt"></i>
        </div>
        <div class="info-content">
          <h4>交易记录</h4>
          <p>查看所有交易明细</p>
          <small>包含充值、支付、提现记录</small>
        </div>
        <i class="fa fa-angle-right"></i>
      </div>

      <div class="info-card" @click="showRepayDialog">
        <div class="info-icon">
          <i class="fas fa-hand-holding-usd"></i>
        </div>
        <div class="info-content">
          <h4>信用卡还款</h4>
          <p v-if="walletBalance.overdraftAmount > 0">当前透支：¥{{ formatPrice(walletBalance.overdraftAmount) }}</p>
          <p v-else>偿还透支金额，避免逾期费用</p>
          <small>优先偿还利息，再偿还本金</small>
        </div>
        <i class="fa fa-angle-right"></i>
      </div>

      <div class="info-card" @click="showOverdraftInfo">
        <div class="info-icon">
          <i class="fas fa-credit-card"></i>
        </div>
        <div class="info-content">
          <h4>透支服务</h4>
          <p>最高可透支{{ userVipLevel?.overdraftMultiplier || 1.0 }}倍余额</p>
          <small>根据VIP等级享受不同透支额度</small>
        </div>
        <i class="fa fa-angle-right"></i>
      </div>

      <div class="info-card" @click="showRechargeBonusInfo">
        <div class="info-icon">
          <i class="fas fa-gift"></i>
        </div>
        <div class="info-content">
          <h4>充值奖励</h4>
          <p>充值满额即享额外奖励</p>
          <small>具体规则以活动页面为准</small>
        </div>
        <i class="fa fa-angle-right"></i>
      </div>

      <div class="info-card" @click="showWithdrawInfo">
        <div class="info-icon">
          <i class="fas fa-money-bill-wave"></i>
        </div>
        <div class="info-content">
          <h4>提现服务</h4>
          <p>快速到账，安全便捷</p>
          <small>支持多种提现方式，详情见说明</small>
        </div>
        <i class="fa fa-angle-right"></i>
      </div>
    </div>

    <!-- 充值对话框 -->
    <div class="modal" v-if="rechargeDialogVisible" @click="closeRechargeDialog">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>充值</h3>
          <i class="fa fa-times" @click="closeRechargeDialog"></i>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>充值金额</label>
            <input
              type="number"
              v-model="rechargeAmount"
              placeholder="请输入充值金额"
              step="0.01"
              min="0.01"
            />
          </div>
          <div class="quick-amounts">
            <button
              v-for="amount in quickAmounts"
              :key="amount"
              @click="rechargeAmount = amount"
            >
              {{ amount }}元
            </button>
          </div>
          <div class="tips">
            <i class="fa fa-info-circle"></i>
            <span>充值可能享有额外奖励，具体以实际到账为准</span>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeRechargeDialog">取消</button>
          <button class="confirm-btn" @click="confirmRecharge" :disabled="recharging">
            {{ recharging ? '充值中...' : '确认充值' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 提现对话框 -->
    <div class="modal" v-if="withdrawDialogVisible" @click="closeWithdrawDialog">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>提现</h3>
          <i class="fa fa-times" @click="closeWithdrawDialog"></i>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>提现金额</label>
            <input
              type="number"
              v-model="withdrawAmount"
              placeholder="请输入提现金额"
              step="0.01"
              min="0.01"
              :max="walletBalance.availableBalance"
            />
          </div>
          <div class="balance-tip">
            可提现余额：&#165;{{ formatPrice(walletBalance.availableBalance) }}
          </div>
          <div class="tips">
            <i class="fa fa-info-circle"></i>
            <span>提现将收取一定手续费，实际到账金额以系统计算为准</span>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeWithdrawDialog">取消</button>
          <button class="confirm-btn" @click="confirmWithdraw" :disabled="withdrawing">
            {{ withdrawing ? '提现中...' : '确认提现' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 透支说明对话框 -->
    <div class="modal" v-if="overdraftDialogVisible" @click="closeOverdraftDialog">
      <div class="modal-content info-modal" @click.stop>
        <div class="modal-header">
          <h3>透支服务说明</h3>
          <i class="fa fa-times" @click="closeOverdraftDialog"></i>
        </div>
        <div class="modal-body">
          <div class="info-section">
            <h4><i class="fas fa-info-circle"></i> 什么是透支服务？</h4>
            <p>透支服务允许您在余额不足时，依然可以使用钱包进行支付，最高可透支额度为可用余额的<span class="highlight">{{ userVipLevel?.overdraftMultiplier || 1.0 }}倍</span>。</p>
          </div>

          <div class="info-section">
            <h4><i class="fas fa-star"></i> 透支规则</h4>
            <div class="vip-privileges" v-if="overdraftRules && overdraftRules.length > 0">
              <div class="privilege-item" v-for="rule in overdraftRules" :key="rule.id">
                <span class="privilege-name">{{ rule.name || '透支服务' }}</span>
                <span class="privilege-value">
                  <span v-if="rule.overdraftLimit">限额：{{ formatPrice(rule.overdraftLimit) }}元</span>
                  <span v-if="rule.dailyInterestRate">日利率：{{ (rule.dailyInterestRate * 100).toFixed(4) }}%</span>
                  <span v-if="rule.gracePeriodDays">宽限期：{{ rule.gracePeriodDays }}天</span>
                </span>
              </div>
            </div>
            <div v-else class="no-data-tip">
              <i class="fas fa-info-circle"></i>
              <span>暂无透支规则数据</span>
            </div>
          </div>

          <div class="info-section">
            <h4><i class="fas fa-exclamation-triangle"></i> 还款说明</h4>
            <ul class="info-list">
              <li>透支金额需要在<strong>30天内</strong>还清</li>
              <li>还款时需支付相应的利息，按日计息</li>
              <li>VIP等级越高，利息折扣越大</li>
              <li>逾期未还清将影响您的信用等级</li>
            </ul>
          </div>

          <div class="info-section">
            <h4><i class="fas fa-shield-alt"></i> 使用提示</h4>
            <ul class="info-list">
              <li>请合理使用透支功能，避免过度消费</li>
              <li>建议及时还款，保持良好的信用记录</li>
              <li>如有疑问请联系客服</li>
            </ul>
          </div>
        </div>
        <div class="modal-footer">
          <button class="confirm-btn" @click="closeOverdraftDialog">我知道了</button>
        </div>
      </div>
    </div>

    <!-- 充值奖励说明对话框 -->
    <div class="modal" v-if="rechargeBonusDialogVisible" @click="closeRechargeBonusDialog">
      <div class="modal-content info-modal" @click.stop>
        <div class="modal-header">
          <h3>充值奖励说明</h3>
          <i class="fa fa-times" @click="closeRechargeBonusDialog"></i>
        </div>
        <div class="modal-body">
          <div class="info-section">
            <h4><i class="fas fa-gift"></i> 什么是充值奖励？</h4>
            <p>为感谢您的支持，我们为每次充值提供<strong>额外奖励</strong>，奖励金额根据充值金额和当前活动而定。</p>
          </div>

          <div class="info-section">
            <h4><i class="fas fa-percentage"></i> 奖励规则</h4>
            <div class="bonus-rules" v-if="rechargeRules && rechargeRules.length > 0">
              <div class="bonus-item" v-for="rule in rechargeRules" :key="rule.id">
                <span class="bonus-range">{{ rule.name || '充值奖励' }}</span>
                <span class="bonus-value">
                  <span v-if="rule.minAmount">满{{ formatPrice(rule.minAmount) }}元</span>
                  <span v-if="rule.bonusAmount && rule.bonusAmount > 0">奖励{{ formatPrice(rule.bonusAmount) }}元</span>
                  <span v-else-if="rule.bonusRate && rule.bonusRate > 0">奖励{{ (rule.bonusRate * 100).toFixed(0) }}%</span>
                </span>
              </div>
            </div>
            <div v-else class="no-data-tip">
              <i class="fas fa-info-circle"></i>
              <span>暂无充值奖励规则</span>
            </div>
          </div>

          <div class="info-section">
            <h4><i class="fas fa-clock"></i> 奖励发放</h4>
            <ul class="info-list">
              <li>奖励在充值成功后<strong>立即到账</strong></li>
              <li>奖励金额可直接用于消费或提现</li>
              <li>奖励不计入VIP升级的累计充值金额</li>
            </ul>
          </div>

          <div class="info-section">
            <h4><i class="fas fa-calendar-alt"></i> 活动说明</h4>
            <ul class="info-list">
              <li>充值奖励活动长期有效，规则可能根据运营策略调整</li>
              <li>具体奖励金额以充值页面显示为准</li>
              <li>如有疑问请联系客服</li>
            </ul>
          </div>

          <div class="bonus-example">
            <h5>举例说明</h5>
            <p>假设您充值<strong>100元</strong>，系统将奖励您<strong>8元</strong>，实际到账<strong>108元</strong>。</p>
          </div>
        </div>
        <div class="modal-footer">
          <button class="confirm-btn" @click="closeRechargeBonusDialog">我知道了</button>
        </div>
      </div>
    </div>

    <!-- 还款对话框 -->
    <div class="modal" v-if="repayDialogVisible" @click="closeRepayDialog">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>还款</h3>
          <i class="fa fa-times" @click="closeRepayDialog"></i>
        </div>
        <div class="modal-body">
          <div class="overdraft-status">
            <div class="status-item">
              <span>当前透支金额</span>
              <span class="amount">¥{{ formatPrice(walletBalance.overdraftAmount || 0) }}</span>
            </div>
            <div class="status-item">
              <span>可用余额</span>
              <span class="amount">¥{{ formatPrice(walletBalance.availableBalance) }}</span>
            </div>
          </div>
          <div class="form-group">
            <label>还款金额</label>
            <input
              type="number"
              v-model="repayAmount"
              placeholder="请输入还款金额"
              step="0.01"
              min="0.01"
              :max="walletBalance.availableBalance"
            />
          </div>
          <div class="balance-tip">
            可还款余额：¥{{ formatPrice(walletBalance.availableBalance) }}
          </div>
          <div class="tips">
            <i class="fa fa-info-circle"></i>
            <span>还款将优先偿还利息，再偿还本金</span>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeRepayDialog">取消</button>
          <button class="confirm-btn" @click="confirmRepay" :disabled="repaying">
            {{ repaying ? '还款中...' : '确认还款' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 提现服务说明对话框 -->
    <div class="modal" v-if="withdrawInfoDialogVisible" @click="closeWithdrawInfoDialog">
      <div class="modal-content info-modal" @click.stop>
        <div class="modal-header">
          <h3>提现服务说明</h3>
          <i class="fa fa-times" @click="closeWithdrawInfoDialog"></i>
        </div>
        <div class="modal-body">
          <div class="info-section">
            <h4><i class="fas fa-money-bill-wave"></i> 什么是提现服务？</h4>
            <p>提现服务允许您将钱包中的可用余额<strong>提现到银行卡</strong>，方便快捷，随时到账。</p>
          </div>

          <div class="info-section">
            <h4><i class="fas fa-list"></i> 提现规则</h4>
            <!-- 调试信息 -->
            <div style="font-size: 12px; color: red; margin-bottom: 10px;">
              
            </div>
            <div class="withdraw-rules" v-if="withdrawRules && withdrawRules.length > 0">
              <div class="rule-item" v-for="rule in withdrawRules" :key="rule.id">
                <!-- 如果有描述字段，优先显示描述 -->
                <div v-if="rule && rule.comment" class="rule-row rule-desc">
                  <i class="fas fa-info-circle"></i>
                  <span>{{ rule.comment }}</span>
                </div>
                <!-- 如果没有描述，显示具体的费率信息 -->
                <div v-else-if="rule && rule.feeRate" class="rule-row">
                  <i class="fas fa-percentage"></i>
                  <span>手续费率：<strong>{{ (rule.feeRate * 100).toFixed(2) }}%</strong></span>
                </div>
                <div v-else-if="rule && (rule.minFee || rule.maxFee)" class="rule-row">
                  <i class="fas fa-coins"></i>
                  <span>
                    <span v-if="rule.minFee">最低手续费：<strong>{{ formatPrice(rule.minFee) }}元</strong></span>
                    <span v-if="rule.maxFee">，最高手续费：<strong>{{ formatPrice(rule.maxFee) }}元</strong></span>
                  </span>
                </div>
                <!-- 如果都没有，显示规则名称 -->
                <div v-else-if="rule && rule.name" class="rule-row">
                  <i class="fas fa-info-circle"></i>
                  <span>{{ rule.name }}</span>
                </div>
              </div>
            </div>
            <div v-else class="no-data-tip">
              <i class="fas fa-info-circle"></i>
              <span>暂无提现规则数据</span>
            </div>
          </div>

          <div class="info-section">
            <h4><i class="fas fa-clock"></i> 到账时间</h4>
            <ul class="info-list">
              <li>工作日提现：<strong>2小时内到账</strong></li>
              <li>非工作日提现：<strong>1-3个工作日到账</strong></li>
              <li>单笔金额超过5万元：可能需要更长时间处理</li>
            </ul>
          </div>

          <div class="info-section">
            <h4><i class="fas fa-exclamation-triangle"></i> 注意事项</h4>
            <ul class="info-list">
              <li>提现前请确保银行卡信息准确无误</li>
              <li>冻结金额无法提现，需解冻后操作</li>
              <li>提现过程中如有问题请联系客服</li>
              <li>每月提现次数过多可能收取额外费用</li>
            </ul>
          </div>
        </div>
        <div class="modal-footer">
          <button class="confirm-btn" @click="closeWithdrawInfoDialog">我知道了</button>
        </div>
      </div>
    </div>

    <!-- 底部菜单（根据用户角色显示不同导航） -->
    <div v-if="isBusinessUser" class="business-bottom-bar">
      <div class="bottom-btn" @click="goToBusinessHome">
        <i class="fas fa-home"></i>
        <span>首页</span>
      </div>
      <div class="bottom-btn" @click="goToBusinessOrders">
        <i class="fas fa-clipboard-list"></i>
        <span>订单</span>
      </div>
      <div class="bottom-btn" @click="goToBusinessData">
        <i class="fas fa-chart-line"></i>
        <span>数据</span>
      </div>
      <div class="bottom-btn active" @click="goToBusinessProfile">
        <i class="fas fa-user"></i>
        <span>我的</span>
      </div>
    </div>
    <Footer v-else></Footer>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import Footer from '../components/Footer.vue';
import { walletAPI } from '@/api/wallet.js';
import { userAPI } from '@/api/user.js';
import { rulesAPI } from '@/api/rules.js';

const router = useRouter();

// 检测是否为商家用户
const isBusinessUser = ref(false);

// 检测用户角色
const checkUserRole = () => {
  const userRole = sessionStorage.getItem('userRole');
  isBusinessUser.value = userRole === 'BUSINESS';
};

// 钱包余额信息
const walletBalance = ref({
  walletId: null,
  userId: null,
  availableBalance: 0,
  frozenBalance: 0
});

// 充值相关
const rechargeDialogVisible = ref(false);
const rechargeAmount = ref('');
const recharging = ref(false);
const quickAmounts = [10, 50, 100, 200, 500, 1000];

// 提现相关
const withdrawDialogVisible = ref(false);
const withdrawAmount = ref('');
const withdrawing = ref(false);

// 还款相关
const repayDialogVisible = ref(false);
const repayAmount = ref('');
const repaying = ref(false);

// VIP信息
const userVipLevel = ref(null);

// 透支说明对话框
const overdraftDialogVisible = ref(false);

// 充值奖励说明对话框
const rechargeBonusDialogVisible = ref(false);

// 充值奖励规则
const rechargeRules = ref([]);

// 透支规则
const overdraftRules = ref([]);

// 提现规则
const withdrawRules = ref([]);

// VIP等级数据
const vipLevelsData = ref([]);

// 提现服务说明对话框
const withdrawInfoDialogVisible = ref(false);

// 获取当前用户ID
const getCurrentUserId = async () => {
  try {
    // 使用getSessionStorage工具函数获取userId（会自动JSON.parse）
    const { getSessionStorage } = await import('@/common.js');
    const userId = getSessionStorage('userId');
    return userId ? parseInt(userId) : null;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    return null;
  }
};

// 获取钱包余额
const fetchWalletBalance = async () => {
  const userId = await getCurrentUserId();
  console.log("userid   " + userId);
  if (!userId) {
    alert('请先登录');
    router.push('/login');
    return;
  }

  try {
    const response = await walletAPI.getBalance(userId);
    console.log('钱包余额响应:', response);

    if (response.data && response.data.success) {
      walletBalance.value = response.data.data;
    } else if (response.data) {
      walletBalance.value = response.data;
    } else {
      throw new Error('获取钱包余额失败');
    }
  } catch (error) {
    console.error('获取钱包余额失败:', error);
    if (error.response && error.response.status === 404) {
      // 钱包不存在，初始化余额为0
      walletBalance.value = {
        walletId: null,
        userId: userId,
        availableBalance: 0,
        frozenBalance: 0
      };
    } else {
      alert('获取钱包信息失败，请重试');
    }
  }
};

// 获取用户VIP信息
const fetchUserVipInfo = async () => {
  try {
    const response = await userAPI.information();
    if (response.data && response.data.success && response.data.data) {
      const userData = response.data.data;
      if (userData.vipLevel && userData.vipLevelValue > 0) {
        // 获取VIP等级的详细信息
        const vipResponse = await rulesAPI.vip.getAll();
        if (vipResponse.data && vipResponse.data.success && vipResponse.data.data) {
          const vipLevels = vipResponse.data.data;
          const currentVip = vipLevels.find(v => v.level === userData.vipLevelValue);
          if (currentVip) {
            userVipLevel.value = {
              name: userData.vipLevel,
              level: userData.vipLevelValue,
              overdraftMultiplier: currentVip.overdraftMultiplier || 1.0,
              interestDiscount: currentVip.interestDiscount || 1.0
            };
          }
        }
      }
    }
  } catch (error) {
    console.error('获取VIP信息失败:', error);
  }
};

// 获取充值奖励规则
const fetchRechargeRules = async () => {
  try {
    const response = await rulesAPI.recharge.getAll();
    console.log('充值规则原始响应:', response);
    if (response.data && response.data.success && response.data.data) {
      rechargeRules.value = response.data.data;
      console.log('充值规则数据:', rechargeRules.value);
      console.log('充值规则数量:', rechargeRules.value.length);
      if (rechargeRules.value.length > 0) {
        console.log('第一条规则详情:', JSON.stringify(rechargeRules.value[0], null, 2));
      }
    } else {
      console.log('充值规则响应格式不正确:', response.data);
      rechargeRules.value = [];
    }
  } catch (error) {
    console.error('获取充值规则失败:', error);
    rechargeRules.value = [];
  }
};

// 获取透支规则
const fetchOverdraftRules = async () => {
  try {
    const response = await rulesAPI.overdraft.getAll();
    console.log('透支规则原始响应:', response);
    if (response.data && response.data.success && response.data.data) {
      overdraftRules.value = response.data.data;
      console.log('透支规则数据:', overdraftRules.value);
      if (overdraftRules.value.length > 0) {
        console.log('第一条透支规则详情:', JSON.stringify(overdraftRules.value[0], null, 2));
      }
    }
  } catch (error) {
    console.error('获取透支规则失败:', error);
  }
};

// 获取VIP等级数据
const fetchVipLevels = async () => {
  try {
    const response = await rulesAPI.vip.getAll();
    if (response.data && response.data.success && response.data.data) {
      vipLevelsData.value = response.data.data;
    }
  } catch (error) {
    console.error('获取VIP等级失败:', error);
  }
};

// 获取提现规则
const fetchWithdrawRules = async () => {
  try {
    const response = await rulesAPI.withdraw.getAll();
    console.log('提现规则原始响应:', response);
    if (response.data && response.data.success && response.data.data) {
      withdrawRules.value = response.data.data;
      console.log('提现规则数据:', withdrawRules.value);
      console.log('提现规则数量:', withdrawRules.value.length);
      if (withdrawRules.value.length > 0) {
        console.log('第一条提现规则详情:', JSON.stringify(withdrawRules.value[0], null, 2));
        console.log('comment字段值:', withdrawRules.value[0].comment);
      }
    } else {
      console.log('提现规则响应格式不正确:', response.data);
      withdrawRules.value = [];
    }
  } catch (error) {
    console.error('获取提现规则失败:', error);
    withdrawRules.value = [];
  }
};

// 格式化价格
const formatPrice = (price) => {
  if (price === null || price === undefined) return '0.00';
  const num = parseFloat(price);
  return isNaN(num) ? '0.00' : num.toFixed(2);
};

// 显示充值对话框
const showRechargeDialog = () => {
  rechargeAmount.value = '';
  rechargeDialogVisible.value = true;
};

// 关闭充值对话框
const closeRechargeDialog = () => {
  rechargeDialogVisible.value = false;
  rechargeAmount.value = '';
};

// 确认充值
const confirmRecharge = async () => {
  const amount = parseFloat(rechargeAmount.value);
  if (!amount || amount <= 0) {
    alert('请输入有效的充值金额');
    return;
  }

  const userId = await getCurrentUserId();
  if (!userId) {
    alert('请先登录');
    router.push('/login');
    return;
  }

  recharging.value = true;

  try {
    const response = await walletAPI.recharge({
      userId: userId,
      amount: amount
    });

    if (response.data && response.data.success !== false) {
      const result = response.data.data || response.data;
      alert(`充值成功！实际到账：¥${formatPrice(result.actualDeposit || amount)}`);
      closeRechargeDialog();
      // 刷新余额
      await fetchWalletBalance();
    } else {
      alert('充值失败：' + (response.data.message || '请重试'));
    }
  } catch (error) {
    console.error('充值失败:', error);
    alert('充值失败，请重试');
  } finally {
    recharging.value = false;
  }
};

// 显示提现对话框
const showWithdrawDialog = () => {
  if (walletBalance.value.availableBalance <= 0) {
    alert('可用余额不足，无法提现');
    return;
  }
  withdrawAmount.value = '';
  withdrawDialogVisible.value = true;
};

// 关闭提现对话框
const closeWithdrawDialog = () => {
  withdrawDialogVisible.value = false;
  withdrawAmount.value = '';
};

// 显示透支说明对话框
const showOverdraftInfo = () => {
  overdraftDialogVisible.value = true;
};

// 关闭透支说明对话框
const closeOverdraftDialog = () => {
  overdraftDialogVisible.value = false;
};

// 显示充值奖励说明对话框
const showRechargeBonusInfo = () => {
  rechargeBonusDialogVisible.value = true;
};

// 关闭充值奖励说明对话框
const closeRechargeBonusDialog = () => {
  rechargeBonusDialogVisible.value = false;
};

// 显示提现服务说明对话框
const showWithdrawInfo = () => {
  withdrawInfoDialogVisible.value = true;
};

// 关闭提现服务说明对话框
const closeWithdrawInfoDialog = () => {
  withdrawInfoDialogVisible.value = false;
};

// 显示还款对话框
const showRepayDialog = () => {
  if (walletBalance.value.overdraftAmount <= 0) {
    alert('无透支金额，无需还款');
    return;
  }
  if (walletBalance.value.availableBalance <= 0) {
    alert('可用余额不足，无法还款');
    return;
  }
  repayAmount.value = '';
  repayDialogVisible.value = true;
};

// 关闭还款对话框
const closeRepayDialog = () => {
  repayDialogVisible.value = false;
  repayAmount.value = '';
};

// 确认还款
const confirmRepay = async () => {
  const amount = parseFloat(repayAmount.value);
  if (!amount || amount <= 0) {
    alert('请输入有效的还款金额');
    return;
  }

  if (amount > walletBalance.value.availableBalance) {
    alert('还款金额超过可用余额');
    return;
  }

  const userId = await getCurrentUserId();
  if (!userId) {
    alert('请先登录');
    router.push('/login');
    return;
  }

  repaying.value = true;

  try {
    const response = await walletAPI.repay({
      userId: userId,
      amount: amount
    });

    if (response.data && response.data.success !== false) {
      const result = response.data.data || response.data;
      alert(`还款成功！\n还款金额：¥${formatPrice(amount)}\n剩余透支：¥${formatPrice(result.remainingOverdraft || 0)}`);
      closeRepayDialog();
      // 刷新余额
      await fetchWalletBalance();
    } else {
      const errorMsg = response.data.message || response.data.msg || '请重试';
      alert('还款失败：' + errorMsg);
    }
  } catch (error) {
    console.error('还款失败:', error);
    const errorMsg = error.response?.data?.message || error.response?.data?.msg || error.message || '请重试';
    alert('还款失败：' + errorMsg);
  } finally {
    repaying.value = false;
  }
};

// 确认提现
const confirmWithdraw = async () => {
  const amount = parseFloat(withdrawAmount.value);
  if (!amount || amount <= 0) {
    alert('请输入有效的提现金额');
    return;
  }

  if (amount > walletBalance.value.availableBalance) {
    alert('提现金额超过可用余额');
    return;
  }

  const userId = await getCurrentUserId();
  if (!userId) {
    alert('请先登录');
    router.push('/login');
    return;
  }

  withdrawing.value = true;

  try {
    console.log('开始提现，userId:', userId, 'amount:', amount);
    const response = await walletAPI.withdraw({
      userId: userId,
      amount: amount
    });

    console.log('提现API响应:', response);

    if (response.data && response.data.success !== false) {
      const result = response.data.data || response.data;
      const actualAmount = result.actualWithdraw || (amount - (result.fee || 0));
      alert(`提现成功！实际到账：¥${formatPrice(actualAmount)}\n手续费：¥${formatPrice(result.fee || 0)}`);
      closeWithdrawDialog();
      // 刷新余额
      await fetchWalletBalance();
    } else {
      const errorMsg = response.data.message || response.data.msg || '请重试';
      console.error('提现失败响应:', response.data);
      alert('提现失败：' + errorMsg);
    }
  } catch (error) {
    console.error('提现失败:', error);
    console.error('错误详情:', error.response);
    const errorMsg = error.response?.data?.message || error.response?.data?.msg || error.message || '请重试';
    alert('提现失败：' + errorMsg);
  } finally {
    withdrawing.value = false;
  }
};

// 前往交易记录页面
const goToTransactions = () => {
  router.push('/transactionList');
};

// 返回
const goBack = () => {
  router.back();
};

onMounted(() => {
  checkUserRole(); // 检测用户角色
  fetchWalletBalance();
  fetchUserVipInfo(); // 获取VIP信息
  fetchRechargeRules(); // 获取充值奖励规则
  fetchOverdraftRules(); // 获取透支规则
  fetchVipLevels(); // 获取VIP等级数据
  fetchWithdrawRules(); // 获取提现规则
});

// 商家导航跳转函数
const goToBusinessHome = () => {
  router.push('/BusinessEnd');
};

const goToBusinessOrders = () => {
  router.push('/business-orders');
};

const goToBusinessData = () => {
  router.push('/business-data');
};

const goToBusinessProfile = () => {
  router.push('/business-profile');
};
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 15vw;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4vw;
}

.wrapper header i {
  font-size: 6vw;
  cursor: pointer;
}

/****************** 余额展示部分 ******************/
.balance-section {
  margin-top: 14vw;
  padding: 4vw;
}

.balance-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 3vw;
  padding: 6vw;
  color: white;
  box-shadow: 0 2vw 4vw rgba(0, 0, 0, 0.1);
}

.balance-title {
  font-size: 3.5vw;
  opacity: 0.9;
  margin-bottom: 2vw;
}

.balance-amount {
  font-size: 10vw;
  font-weight: bold;
  margin-bottom: 4vw;
}

.balance-detail {
  display: flex;
  justify-content: space-between;
  padding-top: 3vw;
  border-top: 1px solid rgba(255, 255, 255, 0.3);
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 1vw;
}

.detail-item span:first-child {
  font-size: 3vw;
  opacity: 0.8;
}

.detail-item span:last-child {
  font-size: 4vw;
  font-weight: bold;
}

/****************** 操作按钮部分 ******************/
.action-section {
  padding: 4vw;
}

.action-buttons {
  display: flex;
  gap: 4vw;
}

.action-buttons button {
  flex: 1;
  height: 12vw;
  border: none;
  border-radius: 2vw;
  font-size: 4vw;
  font-weight: bold;
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 2vw;
  transition: all 0.3s;
}

.recharge-btn {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.recharge-btn:hover {
  transform: translateY(-0.5vw);
  box-shadow: 0 2vw 4vw rgba(245, 87, 108, 0.3);
}

.withdraw-btn {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.withdraw-btn:hover {
  transform: translateY(-0.5vw);
  box-shadow: 0 2vw 4vw rgba(79, 172, 254, 0.3);
}

.action-buttons button i {
  font-size: 5vw;
}

/****************** 冻结资金提示 ******************/
.frozen-notice {
  display: flex;
  align-items: flex-start;
  gap: 3vw;
  padding: 4vw;
  margin-top: 4vw;
  background: linear-gradient(135deg, #fff5e6 0%, #ffe6cc 100%);
  border-radius: 2vw;
  border-left: 1vw solid #ff9800;
}

.frozen-notice i {
  font-size: 5vw;
  color: #ff9800;
  margin-top: 0.5vw;
}

.frozen-info {
  flex: 1;
}

.frozen-title {
  font-size: 4vw;
  font-weight: bold;
  color: #ff9800;
  margin: 0 0 1vw 0;
}

.frozen-desc {
  font-size: 3.5vw;
  color: #666;
  margin: 0.5vw 0;
}

/****************** 信息卡片 ******************/
.info-cards {
  margin: 4vw;
  display: flex;
  flex-direction: column;
  gap: 3vw;
}

.info-card {
  display: flex;
  align-items: center;
  padding: 4vw;
  background: white;
  border-radius: 2vw;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 0.5vw 2vw rgba(0, 0, 0, 0.05);
}

.info-card:hover {
  transform: translateY(-0.5vw);
  box-shadow: 0 1vw 3vw rgba(0, 0, 0, 0.1);
}

.info-icon {
  width: 12vw;
  height: 12vw;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 3vw;
  font-size: 5.5vw;
}

.info-card:nth-child(1) .info-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.info-card:nth-child(2) .info-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.info-content {
  flex: 1;
}

.info-content h4 {
  font-size: 4.5vw;
  color: #333;
  margin: 0 0 1vw 0;
}

.info-content p {
  font-size: 3.5vw;
  color: #666;
  margin: 0 0 0.5vw 0;
}

.info-content small {
  font-size: 3vw;
  color: #999;
}

.info-card i:last-child {
  font-size: 4vw;
  color: #ccc;
  margin-left: 2vw;
}

/****************** 对话框 ******************/
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.modal-content {
  background: white;
  width: 80%;
  max-width: 500px;
  border-radius: 2vw;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4vw;
  border-bottom: 1px solid #f0f0f0;
}

.modal-header h3 {
  font-size: 4.5vw;
  color: #333;
  margin: 0;
}

.modal-header i {
  font-size: 5vw;
  color: #999;
  cursor: pointer;
}

.modal-body {
  padding: 4vw;
}

.form-group {
  margin-bottom: 4vw;
}

.form-group label {
  display: block;
  font-size: 3.5vw;
  color: #666;
  margin-bottom: 2vw;
}

.form-group input {
  width: 100%;
  height: 10vw;
  border: 1px solid #ddd;
  border-radius: 1vw;
  padding: 0 3vw;
  font-size: 4vw;
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
  border-color: #0097ff;
}

.quick-amounts {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 2vw;
  margin-bottom: 4vw;
}

.quick-amounts button {
  height: 10vw;
  border: 1px solid #ddd;
  background: white;
  border-radius: 1vw;
  font-size: 3.5vw;
  color: #333;
  cursor: pointer;
  transition: all 0.3s;
}

.quick-amounts button:hover {
  border-color: #0097ff;
  color: #0097ff;
  background: #f0f8ff;
}

.balance-tip {
  padding: 2vw 3vw;
  background: #fff7e6;
  border-radius: 1vw;
  font-size: 3.5vw;
  color: #ff8c00;
  margin-bottom: 3vw;
}

/* 透支状态显示 */
.overdraft-status {
  background: linear-gradient(135deg, #fff5e6 0%, #ffe6cc 100%);
  border-radius: 1vw;
  padding: 3vw;
  margin-bottom: 4vw;
  border-left: 1vw solid #ff9800;
}

.overdraft-status .status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 2vw 0;
  font-size: 4vw;
  color: #333;
}

.overdraft-status .status-item:first-child {
  border-bottom: 1px dashed #ff9800;
}

.overdraft-status .status-item .amount {
  font-size: 4.5vw;
  font-weight: bold;
  color: #ff6b00;
}

.tips {
  display: flex;
  align-items: flex-start;
  gap: 2vw;
  padding: 2vw 3vw;
  background: #f0f8ff;
  border-radius: 1vw;
  font-size: 3vw;
  color: #666;
}

.tips i {
  color: #0097ff;
  margin-top: 0.5vw;
}

.modal-footer {
  display: flex;
  gap: 3vw;
  padding: 4vw;
  border-top: 1px solid #f0f0f0;
}

.modal-footer button {
  flex: 1;
  height: 10vw;
  border: none;
  border-radius: 1vw;
  font-size: 4vw;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.cancel-btn:hover {
  background: #e8e8e8;
}

.confirm-btn {
  background: #0097ff;
  color: white;
}

.confirm-btn:hover:not(:disabled) {
  background: #0086e6;
}

.confirm-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/****************** 详细信息对话框 ******************/
.info-modal {
  max-width: 90%;
  max-height: 85vh;
  overflow-y: auto;
}

.info-modal .modal-body {
  padding: 3vw 4vw;
  max-height: 60vh;
  overflow-y: auto;
}

.info-section {
  margin-bottom: 4vw;
  padding-bottom: 3vw;
  border-bottom: 1px solid #f0f0f0;
}

.info-section:last-child {
  border-bottom: none;
}

.info-section h4 {
  font-size: 4vw;
  color: #333;
  margin: 0 0 2vw 0;
  display: flex;
  align-items: center;
  gap: 1.5vw;
}

.info-section h4 i {
  color: #0097ff;
  font-size: 4.5vw;
}

.info-section p {
  font-size: 3.5vw;
  color: #666;
  line-height: 1.6;
  margin: 0;
}

.info-section .highlight {
  color: #ff6b6b;
  font-weight: bold;
}

.vip-privileges {
  display: flex;
  flex-direction: column;
  gap: 2vw;
  margin-top: 2vw;
}

.privilege-item {
  display: flex;
  align-items: center;
  padding: 2vw 3vw;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 1vw;
  gap: 3vw;
}

.privilege-name {
  font-size: 3.5vw;
  font-weight: bold;
  color: #333;
  min-width: 15vw;
  text-align: center;
  padding: 1vw 2vw;
  background: white;
  border-radius: 0.5vw;
}

.privilege-value {
  font-size: 3.5vw;
  color: #666;
  flex: 1;
}

.bonus-rules {
  display: flex;
  flex-direction: column;
  gap: 2vw;
  margin-top: 2vw;
}

.bonus-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 2.5vw 3vw;
  background: linear-gradient(135deg, #fff5e6 0%, #ffe6cc 100%);
  border-radius: 1vw;
  border-left: 1vw solid #ff9800;
}

.bonus-range {
  font-size: 3.8vw;
  color: #333;
  font-weight: bold;
}

.bonus-value {
  font-size: 3.8vw;
  color: #ff6b6b;
  font-weight: bold;
}

.info-list {
  list-style: none;
  padding: 0;
  margin: 2vw 0 0 0;
}

.info-list li {
  font-size: 3.5vw;
  color: #666;
  line-height: 1.8;
  margin-bottom: 1.5vw;
  padding-left: 4vw;
  position: relative;
}

.info-list li:before {
  content: '•';
  position: absolute;
  left: 1.5vw;
  color: #0097ff;
  font-size: 4vw;
}

.bonus-example {
  margin-top: 4vw;
  padding: 3vw;
  background: linear-gradient(135deg, #e0f7fa 0%, #b2ebf2 100%);
  border-radius: 1.5vw;
  border-left: 1vw solid #00acc1;
}

.bonus-example h5 {
  font-size: 4vw;
  color: #00838f;
  margin: 0 0 2vw 0;
}

.bonus-example p {
  font-size: 3.5vw;
  color: #00695c;
  line-height: 1.6;
  margin: 0;
}

.no-data-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 2vw;
  padding: 4vw;
  background: #f5f5f5;
  border-radius: 1vw;
  font-size: 3.5vw;
  color: #999;
}

.no-data-tip i {
  font-size: 4vw;
  color: #ccc;
}

.withdraw-rules {
  display: flex;
  flex-direction: column;
  gap: 3vw;
  margin-top: 2vw;
}

.rule-item {
  padding: 3vw;
  background: linear-gradient(135deg, #f0f8ff 0%, #e0f0ff 100%);
  border-radius: 1.5vw;
  border-left: 1vw solid #0097ff;
}

.rule-row {
  display: flex;
  align-items: center;
  gap: 2vw;
  padding: 1.5vw 0;
  font-size: 3.8vw;
  color: #333;
}

.rule-row:not(:last-child) {
  border-bottom: 1px dashed #ddd;
}

.rule-row i {
  color: #0097ff;
  font-size: 4vw;
  min-width: 5vw;
}

.rule-row strong {
  color: #0097ff;
}

.rule-row.rule-desc {
  background: linear-gradient(135deg, #fff5e6 0%, #ffe6cc 100%);
  border-radius: 1vw;
  padding: 3vw;
  border-left: 1vw solid #ff9800;
  font-size: 3.8vw;
  color: #333;
  font-weight: 500;
  line-height: 1.6;
}

.rule-row.rule-desc i {
  color: #ff9800;
  font-size: 4.5vw;
}

/****************** 商家底部导航栏 ******************/
/* 商家底部操作栏 */
.business-bottom-bar {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 60px;
  background-color: white;
  display: flex;
  justify-content: space-around;
  align-items: center;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.business-bottom-bar .bottom-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 8px;
  color: #666;
  font-size: 12px;
  text-align: center;
  transition: color 0.2s;
}

.business-bottom-bar .bottom-btn i {
  font-size: 20px;
  margin-bottom: 3px;
}

.business-bottom-bar .bottom-btn.active {
  color: #0097ff;
}

.business-bottom-bar .bottom-btn:active {
  transform: scale(0.95);
}
</style>
